<template>
  <div style="display: contents;">
    <div class="loading" v-show="showLoading" :style="{ 'opacity': showLoadingOpacity }">
      <div class="icon">
        <i class="fa-solid fa-circle-notch "></i>
        <p>正在自动登录</p>
      </div>
    </div>

    <!-- 添加绑定账号modal -->
    <div class="add-user-modal" v-show="showAddUserModal">
      <div style="margin-bottom:10px">
        <label>用户名：</label>
        <input v-model="bindUser.name" type="text" />
      </div>
      <div style="margin-bottom:10px">
        <label>密&nbsp;&nbsp;&nbsp;码：</label>
        <input v-model="bindUser.password" type="password" />
      </div>
      <div>
        <span class="add-user-bottom" @click="addBindUser">
          添加
        </span>
        <span class="add-user-bottom-cancel" @click="showAddUserModal = false">
          取消
        </span>
      </div>
    </div>
    <!-- 添加绑定账号modal end -->

    <!-- 选择账号modal -->
    <div class="choice-user" v-show="showChoiceUserModal">
      <div class="item" :key="index" v-for="(account, index) in bindUserList"
        @click="showChoiceUserModal = false; changeUser(index)">
        <span class="name" :title="account.name">{{ account.name }}</span>
        <i class="fa-solid fa-trash-can" @click.stop="showChoiceUserModal = false; removeUser(index)"></i>
      </div>
    </div>
    <div class="operation-bar">
      <div class="left">
        <i class="fa fa-arrow-left" title="后退" @click="back"></i>
        <i class="fa fa-arrow-right" title="前进" @click="forward"></i>
        <i class="fa fa-home" title="首页" @click="toHome"></i>
        <i class="fa-solid fa-circle-arrow-right" title="跳转" @click="loadInputUrlByCopy()"></i>
        <i class="fa fa-refresh" :class="{ 'turn': onWebLoading }" title="刷新" @click="refresh"></i>
        <input v-model="showUrl" @keyup.enter="loadInputUrl()" class="url-input" />

      </div>
      <div class="right">
        <div class="choice-user-div" @click="showChoiceUserModal = !showChoiceUserModal">
          <span v-if="!useUser.name">选择账号</span>
          <span v-if="useUser.name">{{ useUser.name }}</span>
          <i class="fa fa-angle-down" v-show="!showChoiceUserModal"></i>
          <i class="fa fa-angle-up" v-show="showChoiceUserModal"></i>
        </div>
        <i class="fa fa-user-plus" @click="showAddUser"></i>
      </div>
    </div>

    <div class="web-div">
      <webview v-on:load-commit='loadCommit($event)' v-on:did-finish-load='didFinishLoad($event)'
        v-on:console-message="consoleMessage($event)" v-on:did-start-loading="startLoading($event)"
        v-on:did-stop-loading="stopLoading($event)" class="webview" :id="'webview-' + webUrl" :src="loadUrl"
        disablewebsecurity></webview>

    </div>
    <!-- web应用 end -->

  </div>
</template>

<script>
import { globalBus } from '@/assets/js/globalBus.js'
import { ut } from '@/assets/js/webViewAutoLogin.js'
import Swal from 'sweetalert2'
var ipcRenderer
var clipboard
if (window.require) {
  ipcRenderer = window.require('electron').ipcRenderer
  clipboard = window.require('electron').clipboard
}
const nedb = require('nedb')

// eslint-disable-next-line new-cap
const webUserBindDb = new nedb({
  filename: '/data/web-user-bind.db',
  autoload: true
})
// eslint-disable-next-line new-cap
const aplaneTypeDb = new nedb({
  filename: '/data/aplane-type.db',
  autoload: true
})
export default {
  name: 'WebViewIndex',
  data() {
    return {
      onWebLoading: false,
      showChoiceUserModal: false,
      bindUserList: [],
      // 编辑的账号
      bindUser: {
        name: '',
        password: ''
      },
      // 当前选用的账号
      useUser: {
        name: '',
        password: ''
      },
      showAddUserModal: false,
      loadUrl: '',
      showUrl: '',
      showLoading: false,
      showLoadingOpacity: 1,
      beforeLoginTime: undefined,
      nowDate: undefined,
      aplaneTodoDb: undefined
    }
  },
  props: ['webUrl'],
  created() {
    globalBus.$on('aPlane_reload', this.loadPlaneDb)
  },
  beforeDestroy() {
    globalBus.$off('aPlane_reload', this.loadPlaneDb)
  },
  mounted() {
    var _this = this
    ut.aotuLogin('src', null)
    this.loadBindUser()
    this.loadUrl = this.webUrl + ''
    this.loadPlaneDb()
  },
  methods: {
    showAddUser() {
      this.showChoiceUserModal = false;
      this.bindUser.name = '';
      this.bindUser.password = '';
      this.showAddUserModal = true;
    },
    // 加载计划
    loadPlaneDb(palne) {
      var date = new Date()
      this.nowDate = date
      // eslint-disable-next-line new-cap
      this.aplaneTodoDb = new nedb({
        filename:
          '/data/aplane-todo_' +
          date.getFullYear() +
          '-' +
          date.getMonth() +
          '.db',
        autoload: true
      })

      if (palne) {
        setTimeout(() => {
          this.addPlane(palne)
        }, 50)
      }
    },
    // 添加计划
    addPlane(palne) {
      // 如果日期不对则重新加载  再添加
      var date = new Date()
      if (
        date.getFullYear() !== this.nowDate.getFullYear() &&
        date.getMonth() !== this.nowDate.getMonth() &&
        date.getDate() !== this.nowDate.getDate()
      ) {
        this.loadPlaneDb(palne)
      }
      var _this = this
      if (palne.type) {
        aplaneTypeDb.find(
          {
            name: palne.type
          },
          function (_err, docs) {
            if (docs.length === 0) {
              aplaneTypeDb.insert(
                {
                  name: palne.type
                },
                (_err, _ret) => { }
              )
            }
          }
        )
      }

      palne.bugId = palne.bugId.trim()
      palne.title = palne.title.trim()
      if (palne.type) {
        palne.type = palne.type.trim()
      }
      _this.aplaneTodoDb.find(
        {
          year: _this.nowDate.getFullYear(),
          moth: _this.nowDate.getMonth(),
          date: _this.nowDate.getDate(),
          title: palne.title
        },
        function (_err, docs) {
          if (docs.length === 0) {
            _this.aplaneTodoDb.insert(
              {
                year: _this.nowDate.getFullYear(),
                moth: _this.nowDate.getMonth(),
                date: _this.nowDate.getDate(),
                bugId: palne.bugId,
                title: palne.title,
                scope: "BUG",
                status: '进行中',
                type: palne.type
              },
              (_err, _docs) => {
                Swal.fire({
                  title: `任务已添加`,
                  icon: 'success'
                })
                globalBus.$emit('aPlane_reload', (_date) => { })
                if (!ipcRenderer) {
                  return
                }
                ipcRenderer.send('mini-plane-refresh')
              }
            )
          } else {
            Swal.fire({
              title: `任务已存在`,
              icon: 'error'
            })
          }
        }
      )
    },
    loadBindUser() {
      var _this = this
      webUserBindDb.find(
        {
          url: _this.webUrl
        },
        function (_err, docs) {
          _this.bindUserList = docs
          if (docs.length > 0) {
            _this.useUser = docs[0]
            for (var i = 0; i < docs.length; i++) {
              if (docs[i].use) {
                _this.useUser = docs[i]
                break
              }
            }
          }
        }
      )
    },
    // 从拷贝粘贴
    loadInputUrlByCopy() {
      let url = clipboard.readText()
      if (url.length > 1000) {
        return
      }
      if (url.indexOf(this.webUrl) >= 0) {
        this.showUrl = url
        var webview = document.getElementById('webview-' + this.webUrl)
        webview.loadURL(this.showUrl)
      }
    },
    loadInputUrl() {
      if (this.showUrl.indexOf(this.webUrl) >= 0) {
        var webview = document.getElementById('webview-' + this.webUrl)
        webview.loadURL(this.showUrl)
      }
    },
    removeUser(index) {
      var _this = this
      Swal.fire({
        title: '确认删除"' + _this.bindUserList[index].name + '"吗?',
        showDenyButton: true,
        showCancelButton: true,
        showConfirmButton: false,
        denyButtonText: `确认`,
        cancelButtonText: `取消`
      }).then((result) => {
        if (result.isDenied) {
          // 删除
          webUserBindDb.remove(
            _this.bindUserList[index],
            {},
            function (_err, _numRemoved) {
              if ((_this.useUser.name = _this.bindUserList[index].name)) {
                _this.useUser.name = ''
              }
              _this.loadBindUser()
            }
          )
        }
      })
    },
    changeUser(index) {
      var _this = this
      var webview = document.getElementById('webview-' + this.webUrl)
      this.useUser = this.bindUserList[index]
      ut.reLogin(this.webUrl, webview)
      webUserBindDb.update(
        {
          use: true
        },
        { $set: { use: false } },
        {},
        function (_err, _numRemoved) {
          webUserBindDb.update(
            {
              _id: _this.useUser._id
            },
            { $set: { use: true } },
            {},
            function (_err, _numRemoved) { }
          )
        }
      )
    },
    // 添加账号绑定
    addBindUser() {
      var _this = this
      this.bindUser.url = this.webUrl
      webUserBindDb.find(
        {
          url: this.webUrl,
          name: this.bindUser.name
        },
        function (_err, docs) {
          if (docs.length > 0) {
            Swal.fire({
              title: `账号已存在`,
              icon: 'error'
            })
            _this.bindUserList = docs
          } else {
            webUserBindDb.insert(_this.bindUser, function (_err, _newDoc) {
              if (_this.bindUserList) {
                _this.bindUserList.push(_this.bindUser)
              } else {
                _this.bindUserList = [_this.bindUser]
              }
              _this.loadBindUser()
              _this.refresh()
            })
          }
        }
      )
      this.showAddUserModal = false
    },
    // 显示隐藏加载框
    showLoadingFun(show) {
      var _this = this
      if (show) {
        _this.showLoading = true
        _this.showLoadingOpacity = 1
      } else {
        _this.showLoadingOpacity = 0
        setTimeout(function () {
          _this.showLoading = false
        }, 800)
      }
    },
    loadCommit(e) {
      if (
        this.beforeLoginTime &&
        new Date().getTime() - this.beforeLoginTime < 3600000
      ) {
        return
      }
      var webview = document.getElementById('webview-' + this.webUrl)
      if (e.url) {
        ut.verifyNeedTo(e.url, webview)
      }
    },
    consoleMessage(e) {
      var msg = e.message
      if (msg.indexOf('awork::') !== 0) {
        return
      }
      msg = msg.replace('awork::', '')
      msg = JSON.parse(msg)
      if (msg.msgType === 'addPlane') {
        this.addPlane(msg)
      }

      if (msg.msgType === 'handleQA') {
        var webview = document.getElementById('webview-' + this.webUrl)
        var content = msg.content.replace('重现步骤', '').replace('[步骤]', '').replace('[结果]', '').replace('[期望]', '')
        ut.handlerBugQAView(webview, msg.id, content.replace(/[\\r\n]+/g, ' '))
      }
    },
    didFinishLoad(_e) {
      // this.onWebLoading = false;
    },
    toHome() {
      var webview = document.getElementById('webview-' + this.webUrl)
      webview.loadURL(this.webUrl)
    },
    startLoading(_e) {
      this.onWebLoading = true
      var webview = document.getElementById('webview-' + this.webUrl)
      var url = webview.getAttribute('src')
      // 自动登录
      var dest = ut.verifySuport(url)
      if (dest) {
        this.showLoadingFun(true)
      }
    },
    // 加载完成时间
    stopLoading(_e) {
      var _this = this
      var webview = document.getElementById('webview-' + this.webUrl)
      var src = webview.getAttribute('src')
      this.showUrl = src
      // 自动登录
      var dest = ut.verifySuport(src)
      if (dest) {
        if (!this.useUser.name) {
          Swal.fire({
            title: `请先在右上角，绑定账号`,
            icon: 'error'
          })
          this.showAddUser()
          _this.showLoadingFun(false)
          this.onWebLoading = false
          return
        }
        dest.name = this.useUser.name
        dest.password = this.useUser.password
        ut.aotuLogin(dest, webview)
        this.beforeLoginTime = new Date().getTime()
        setTimeout(() => {
          _this.showLoadingFun(false)
          _this.onWebLoading = false
        }, 500)
      }
      this.onWebLoading = false
      // 加工网页
      ut.doScript(src, webview)
    },
    refresh() {
      var webview = document.getElementById('webview-' + this.webUrl)
      webview.reloadIgnoringCache()
    },
    back() {
      var webview = document.getElementById('webview-' + this.webUrl)
      if (webview.canGoBack()) {
        webview.goBack()
      }
    },
    forward() {
      var webview = document.getElementById('webview-' + this.webUrl)
      if (webview.canGoForward()) {
        webview.goForward()
      }
    }
  }
}
</script>

<style lang="less">
</style>
